<template>
	<view :style="{ '--colorPrimary': color.primary }">
		<navbar :title="$t('Ai人工智能')"></navbar>
		<view class=" chat" :class="dir">
			<scroll-view scroll-y :scroll-top="scrollTop" @scroll="handleScroll" :scroll-with-animation="true"
				class="body chat-scroll-view">
				<view class="chat-body">
					<view class="chat-item" v-for="(item,index) in responseList">
						<view>
							<view class="to" :class="{ 'ltr': isChinaText(item.text) }" v-if="item.type==1"><MDParserHighlight :resource="item.text"></MDParserHighlight></view>
							<view class="my" v-else>{{item.text}}</view>
							<view  @click="copyText(item.text)" :class="{ 'rtl': isChinaText(item.text) }"> <iconfont icon="icon-fuzhi" size="28"/></view>
						</view>
					</view>
				</view>
				<view class="loading" v-show="loading">
					<span></span>
					<span></span>
					<span></span>
					<span></span>
					<span></span>
					<span></span>
					<span></span>
					<span></span>
					<span></span>

				</view>
			</scroll-view>
			<view class="put ltr">
				<input @confirm="sendMessage" :placeholder="$t('发送消息')" v-model="message" color="aqua"
					style="{background-color: aqua;}" />
				<u-button type="primary" :color="color.primary" icon="checkbox-mark" @click="sendMessage"></u-button>
			</view>

		</view>
	</view>
</template>

<script>
	import config from '../../common/config';
	import text from '../../uni_modules/uview-ui/libs/config/props/text';
	import MDParserHighlight from '../../components/cmder-MDParserHighlight/index.vue'

	export default {
		components: {
			MDParserHighlight
		},
		data() {
			return {
				dir: this.$t("dir"),
				responseText: "",
				message: "",
				responseList: [{
					type: 1,
					text: this.$t('你好,我是新疆圆规文化传媒有限公司发的Ai人工智能机器人,我能为你提供健康咨询,有什么可以帮你的吗')
				}],
				scrollTop: 0,
				loading: false
			}
		},
		mounted() {
			this.scrollToBottom();
		},
		methods: {
			 // 复制文本到剪贴板
			    copyText(text) {
			      if (!text) {
			        uni.showToast({
			          title: "请输入文本",
			          icon: "none",
			        });
			        return;
			      }
			
			      uni.setClipboardData({
			        data: text, // 要复制的文本
			        success: () => {
			          this.isCopied = true;
			          uni.showToast({
			            title: "复制成功",
			            icon: "success",
			          });
			        },
			        fail: (err) => {
			          console.error("复制失败", err);
			          uni.showToast({
			            title: "复制失败",
			            icon: "none",
			          });
			        },
			      });
			    },
			isChe(text){
				console.log("TTTTTT",text,uni.$u.test.chinese(text))
			return uni.$u.test.chinese(text);	
			},
			  isChinaText(text) {
				  var result = text.split(/[。！？,]/);
			      // 正则表达式：匹配中文字符
			      const chineseRegex = /^[\u4e00-\u9fa5a-zA-Z]+$/;
			      return chineseRegex.test(text[0]);
			    },
			scrollToBottom() {
				this.$nextTick(() => {
					this.scrollTop = 99999; // 设置一个足够大的值，确保滚动到底部
				});
			},
			handleScroll(event) {
				// 可以在这里处理滚动事件
				console.log(event);
			},
			async sendRequest() {
				const apiKey = '6cc3f5ac-0569-4819-9836-27953bdbacab'; // ModelScope Token
				const model = 'deepseek-ai/DeepSeek-V3'; // ModelScope Model-Id
				var text = "Hello"
				const response = await uni.request({
					url: config.baseUrl + '/chat?message=' + text,
					method: 'GET',
					responseType: 'text'
				});

				if (response.statusCode === 200) {
					this.responseText = response.data;
				} else {
					console.error('请求失败:', response);
				}
			},
			sendMessage() {
				if (this.loading == false) {

					if (!this.message) {
						uni.showToast({
							title: 'Please enter a message',
							icon: 'none'
						});
						return;
					}
					this.loading = true;
					var list = this.responseList;
					list.push({
						type: 0,
						text: this.message
					})
					this.responseList = list;
					var userInfo = uni.getStorageSync('userInfo')

					var Authorization = userInfo.token;
					var language = uni.getStorageSync('lang') || "zh-CN"
	this.scrollToBottom();
					//		config.header.language =language;

					uni.request({
						url: config.baseUrl + '/generate', // 替换为您的后端服务地址
						method: 'GET',
						data: {
							message: this.message
						},
						header: {
							Authorization,
							language
						},
						success: (res) => {
							this.loading = false
							if (res.statusCode === 200) {
								this.responseText = res.data.result.output.text;
								list.push({
									type: 1,
									text: res.data.result.output.text
								})
								this.responseList = list;
								this.message = ""
							} else {
								uni.showToast({
									title: 'Request failed',
									icon: 'none'
								});
							}
						},
						fail: (err) => {
							console.error('Request failed:', err);
							uni.showToast({
								title: 'Request failed',
								icon: 'none'
							});
						}
					});
				}
			}
		}
	}
</script>

<style lang="scss">
	.chat {
		padding-left: 10px;
		padding-right: 10px;
		height: 89vh;

		overflow: hidden;

		.chat-scroll-view {

			overflow-y: auto;
		}

		.body {
			height: 80vh;

			.chat-body {
				display: list-item;

				overflow: hidden;

				.chat-item {
					font-size: 12px;



					width: 100%;
					margin-top: 5px;
					margin-bottom: 5px;
					overflow: hidden;


					.my {
						text-align: start;
						background-color: var(--color-primary);
						color: #fff;
						padding: 10px;
						border-radius: 6px;

						float: inline-start;


					}

					.to {
					/* 	text-align: end; */
						background-color: #fff;
						color: #000;
						padding: 10px;
						border-radius: 6px;
						float: inline-end;

					}
				}
			}
		}

		.put {
			padding-top: 10px;
			height: 9.5vh;
			display: grid;
			grid-template-columns: 1fr 40px;

			input {
				background-color: azure;
				height: 30px;
				padding: 5px;
				border-top-left-radius: 6px;
				border-bottom-left-radius: 6px;
				font-size: 12px;

			}

		}
	}

	/* From Uiverse.io by satyamchaudharydev */
	.loading {
		--speed-of-animation: 0.9s;
		--gap: 6px;
		--first-color: #4c86f9;
		--second-color: #49a84c;
		--third-color: #f6bb02;
		--fourth-color: #f6bb02;
		--fifth-color: #2196f3;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100px;
		gap: 6px;
		height: 100px;
		margin: 0 auto;
	}

	.loading span {
		width: 4px;
		height: 50px;
		background: var(--first-color);
		animation: scale var(--speed-of-animation) ease-in-out infinite;
	}

	.loading span:nth-child(2) {
		background: var(--second-color);
		animation-delay: -0.8s;
	}

	.loading span:nth-child(3) {
		background: var(--third-color);
		animation-delay: -0.7s;
	}

	.loading span:nth-child(4) {
		background: var(--fourth-color);
		animation-delay: -0.6s;
	}

	.loading span:nth-child(5) {
		background: var(--fifth-color);
		animation-delay: -0.5s;
	}

	.loading span:nth-child(6) {
		background: var(--fifth-color);
		animation-delay: -0.4s;
	}

	.loading span:nth-child(7) {
		background: var(--fifth-color);
		animation-delay: -0.3s;
	}

	.loading span:nth-child(8) {
		background: var(--fifth-color);
		animation-delay: -0.2s;
	}

	.loading span:nth-child(9) {
		background: var(--fifth-color);
		animation-delay: -0.1s;
	}

	@keyframes scale {

		0%,
		40%,
		100% {
			transform: scaleY(0.05);
		}

		20% {
			transform: scaleY(1);
		}
	}
</style>